package leetcode;

public class RemoveNthNodeFromEndOfList19 {
    class ListNode {
        int val;
        ListNode next;

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    // 递归删取
    public ListNode removeNthFromEndOfList(ListNode head, int n) {
        ListNode s = new ListNode(-1, head);
        recursion(s, n);
        return s.next;
    }

    public int recursion(ListNode head, int num) {
        if (head == null) {
            return 0;
        }
        // 下个节点返回nth 这个返回nth+1
        int nth = recursion(head.next, num);
        if (nth == num) {
            head.next = head.next.next;
        }
        return nth + 1;
    }

    // 快慢指针法
    public ListNode removeNthFromEndOfList2(ListNode head, int n) {
        ListNode s = new ListNode(-1,head);
        ListNode p1 = s;
        ListNode p2 = s;
        for (int i = 0; i <= n; i++) {
            p2 = p2.next;
        }
        while (p2 != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        p1.next = p1.next.next;
        return s.next;
    }

}
